﻿using Devonline.AspNetCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Net.Http.Headers;

namespace Devonline.CloudService.Feige;

public static class ServiceExtensions
{
    /// <summary>
    /// 注册默认短消息服务
    /// </summary>
    /// <param name="services"></param>
    /// <param name="endpoint"></param>
    /// <returns></returns>
    public static IServiceCollection AddSmsService(this IServiceCollection services, ISmsEndpoint? endpoint = default)
    {
        if (endpoint is not null)
        {
            services.AddSingleton(endpoint);
            services.AddHttpClient<SmsService>(httpClient =>
            {
                //if (endpoint.Protocol == ProtocolType.Https)
                //{
                //    ServicePointManager.ServerCertificateValidationCallback = (sender, cert, chain, sslPolicyErrors) => true;
                //    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls13 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
                //}

                ArgumentNullException.ThrowIfNull(endpoint.Host);
                httpClient.BaseAddress = new Uri(endpoint.Host);
                httpClient.DefaultRequestHeaders.Add(HeaderNames.AcceptEncoding, "gzip, deflate");
                httpClient.DefaultRequestHeaders.Add(HeaderNames.Accept, "text/html, application/xhtml+xml, */*");
            });

            services.AddScoped<ISmsService, SmsService>();
        }

        return services;
    }

    /// <summary>
    /// 注册短信验证码服务
    /// </summary>
    /// <param name="services"></param>
    /// <param name="endpoint"></param>
    /// <param name="smsModel"></param>
    /// <returns></returns>
    public static IServiceCollection AddSmsCaptchaService(this IServiceCollection services, ISmsEndpoint? endpoint = default, ISmsModel? smsModel = default)
    {
        if (endpoint is not null && smsModel is not null)
        {
            services.AddSmsService(endpoint);
            services.AddSingleton(smsModel);
            services.AddSingleton<ISmsCaptchaService, SmsCaptchaService>();
        }

        return services;
    }
}